<template>
  <div>
    <audio ref="audio" src="" hidden v-on:ended="endedPlay"></audio>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>音乐管理</el-breadcrumb-item>
      <el-breadcrumb-item>音乐列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-button type="primary" style="margin-bottom: 20px" @click="addMusic" icon="el-icon-plus">添加音乐</el-button>
      <el-alert show-icon v-if="isHasMusicTypeId" :title="'这是音乐类型为 '+currentMusicType+' 的音乐~~~'" type="success" close-text="我知道了" style="margin-bottom: 20px"></el-alert>
      <el-alert show-icon v-else title="这是全部音乐~~~" type="success" style="margin-bottom: 20px" close-text="我知道了"></el-alert>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="音乐名称" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.music_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="音乐图片" width="180">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="'http://localhost:3001/'+scope.row.music_pic_url" fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="歌手名称" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.singer_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="音乐类型" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.musictype_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-edit" @click="handleEdit(scope.row)"></el-button>
            <el-button size="mini" icon="el-icon-delete" type="danger" @click="handleDelete(scope.row.musicid)"></el-button>
            <el-button size="mini" type="success" icon="el-icon-video-play" @click="handlePlay(scope.row,scope.$index)">{{scope.$index==playIndex?'暂停':'播放'}}</el-button>
            <el-button size="mini" icon="el-icon-setting" type="primary" @click="handleComment(scope.row.musicid)">评论管理</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 修改音乐的表单 -->
    <!-- id name musictypeId singerId musicurl musicfile picfile (musicurl musicfile二选一) -->
    <el-dialog title="编辑音乐" :visible.sync="dialogFormVisibleEditMusic">
      <el-form :model="form" ref="ruleForm" :rules="rules">
        <el-form-item label="音乐名称" label-width='100px' prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="音乐类型" label-width='100px' prop="musictypeId">
          <el-select v-if="MusicTypeOptions.length!==0" filterable v-model="form.musictypeId" placeholder="请选择">
            <el-option v-for="item in MusicTypeOptions" :key="item.musictypeid" :label="item.musictype_name" :value="item.musictypeid">
            </el-option>
          </el-select>
          <span v-else style="text-decoration:underline;color:#409eff;cursor:pointer;" v-on:click="$router.push('/musictypelist')">请先添加音乐类型！</span>
        </el-form-item>
        <el-form-item label="歌手名称" label-width='100px' prop="singerId">
          <el-select v-if="SingerOptions.length!==0" filterable v-model="form.singerId" placeholder="请选择">
            <el-option v-for="item in SingerOptions" :key="item.singerid" :label="item.singer_name" :value="item.singerid">
            </el-option>
          </el-select>
          <span v-else style="text-decoration:underline;color:#409eff;cursor:pointer;" v-on:click="$router.push('/singerlist')">请先添加歌手！</span>
        </el-form-item>
        <el-alert title="音乐地址和音乐文件任选其一填写即可~~~" close-text="我知道了" type="warning" style="margin-bottom: 20px"></el-alert>
        <el-form-item label="音乐地址" label-width='100px'>
          <el-input v-model="form.musicurl" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="音乐文件" label-width='100px'>
          <el-upload class="upload-demo" :file-list="fileList" :auto-upload="false" :on-change='handleFileChange' :multiple="false" drag action="#" accept="audio/mp3">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="音乐图片" label-width='100px'>
          <el-upload class="avatar-uploader" :auto-upload="false" action="#" accept="image/*" :multiple="false" :on-change="handleImageChange" :show-file-list="false">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
      </div>
    </el-dialog>
    <!-- 评论管理的表格 -->
    <el-dialog title="评论管理" :visible.sync="dialogTableVisible">
      <el-table :data="gridData">
        <el-table-column property="user_nickname" label="用户名称" width="130"></el-table-column>
        <el-table-column property="comment_content" label="评论" width="450"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="handleDeleteComment(scope.row.commentid)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 添加音乐的表单 -->
    <!-- name musictypeId singerId musicurl musicfile picfile (musicurl musicfile二选一) -->
    <el-dialog title="添加音乐" :visible.sync="dialogFormVisibleAddMusic">
      <el-form :model="addForm" ref="ruleForm1" :rules="addMusicRules">
        <el-form-item label="音乐名称" label-width='100px' prop="name">
          <el-input v-model="addForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="音乐类型" label-width='100px' prop="musictypeId">
          <el-select v-if="MusicTypeOptions.length!==0" filterable v-model="addForm.musictypeId" placeholder="请选择">
            <el-option v-for="item in MusicTypeOptions" :key="item.musictypeid" :label="item.musictype_name" :value="item.musictypeid">
            </el-option>
          </el-select>
          <span v-else style="text-decoration:underline;color:#409eff;cursor:pointer;" v-on:click="$router.push('/musictypelist')">请先添加音乐类型！</span>
        </el-form-item>
        <el-form-item label="歌手名称" label-width='100px' prop="singerId">
          <el-select v-if="SingerOptions.length!==0" filterable v-model="addForm.singerId" placeholder="请选择">
            <el-option v-for="item in SingerOptions" :key="item.singerid" :label="item.singer_name" :value="item.singerid">
            </el-option>
          </el-select>
          <span v-else style="text-decoration:underline;color:#409eff;cursor:pointer;" v-on:click="$router.push('/singerlist')">请先添加歌手！</span>
        </el-form-item>
        <el-alert title="音乐地址和音乐文件任选其一填写即可~~~" close-text="我知道了" type="warning" style="margin-bottom: 20px"></el-alert>
        <el-form-item label="音乐地址" label-width='100px'>
          <el-input v-model="addForm.musicurl" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="音乐文件" label-width='100px'>
          <el-upload class="upload-demo" :file-list="addMusicFileList" :auto-upload="false" :on-change='handleFileChangeAddMusic' :multiple="false" drag action="#" accept="audio/mp3">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="音乐图片" label-width='100px' prop="picfile">
          <el-upload class="avatar-uploader" :auto-upload="false" action="#" accept="image/*" :multiple="false" :on-change="handleImageChangeAddMusic" :show-file-list="false">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddMusicForm('ruleForm1')">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getMusicList,
  getMusicListByMusicTypeId,
  deleteMusic,
  getMusicTypeByMusicTypeId,
  getMusicType,
  getSinger,
  editMusic,
  getComment,
  deleteComment,
  addMusic
} from '../../utils/api'
export default {
  data () {
    return {
      // 表格数据
      tableData: [],
      // 当前的音乐类型 如果为'',表示为查看全部音乐 如果不为''则是查看对应的音乐类型的音乐 作为方法的参数
      currentMusicTypeId: '',
      // 当前音乐类型的名称
      currentMusicType: '',
      // 是否是从音乐类型页携带音乐类型id跳转
      isHasMusicTypeId: false,
      // 正在播放音乐的表格行数
      playIndex: 0,
      // 控制修改音乐表单的显示
      dialogFormVisibleEditMusic: false,
      // 控制添加音乐表单的显示
      dialogFormVisibleAddMusic: false,
      // 音乐修改的表单
      // id name musictypeId singerId musicurl musicfile picfile (musicurl musicfile二选一)
      form: {
        name: '',
        musictypeId: '',
        singerId: '',
        musicurl: '',
        id: 0,
        musicfile: null,
        picfile: null
      },
      // 音乐修改表单的校验
      rules: {
        name: [
          { required: true, message: '请输入音乐名称', trigger: 'blur' },
        ],
        musictypeId: [
          { required: true, message: '请选择音乐类型', trigger: 'change' }
        ],
        singerId: [
          { required: true, message: '请选择歌手名称', trigger: 'change' }
        ],
      },
      // 音乐添加表单的校验
      addMusicRules: {
        name: [
          { required: true, message: '请输入音乐名称', trigger: 'blur' },
        ],
        musictypeId: [
          { required: true, message: '请选择音乐类型', trigger: 'change' }
        ],
        singerId: [
          { required: true, message: '请选择歌手名称', trigger: 'change' }
        ],
        picfile: [
          { required: true, message: '请选择歌手图片', trigger: 'change' }
        ]
      },
      // 添加音乐表单
      // name musictypeId singerId musicurl musicfile picfile (musicurl musicfile二选一)
      addForm: {
        name: '',
        musictypeId: '',
        singerId: '',
        musicurl: '',
        musicfile: null,
        picfile: null
      },
      // singer数组
      SingerOptions: [],
      // musictype数组
      MusicTypeOptions: [],
      imageUrl: '',
      // 修改音乐上传文件数组
      fileList: [],
      // 添加音乐上传文件数组
      addMusicFileList: [],
      // 评论管理表格数据
      gridData: [],
      // 控制评论管理表格的显示
      dialogTableVisible: false
    }
  },
  created () {
    // 如果是从音乐类型跳转过来
    if (this.$route.query.musictypeid) {
      this.currentMusicTypeId = Number(this.$route.query.musictypeid);
      this.isHasMusicTypeId = !this.isHasMusicTypeId;
      // 作为方法的参数传递进行发起请求
      this.getMusicLByMusicType(this.currentMusicTypeId);
    } else {
      // 不是从音乐类型跳转过来 获取全部音乐
      this.getMusicL();
    }
  },
  methods: {
    // 添加音乐 准备数据
    addMusic () {
      this.dialogFormVisibleAddMusic = true;
      // 获取musictype 为添加音乐做准备
      this.getMusicTypeL();
      // 获取singer 为添加音乐做准备
      this.getSingerL();
    },
    // 获取musictype 为修改音乐和添加音乐做准备
    async getMusicTypeL () {
      let res = await getMusicType();
      this.MusicTypeOptions = res.data;
    },
    // 获取singer 为修改音乐和添加音乐做准备
    async getSingerL () {
      let res = await getSinger();
      this.SingerOptions = res.data;
    },
    // 修改音乐 准备全部数据
    handleEdit (scope) {
      // id name musictypeId singerId musicurl musicfile picfile (musicurl musicfile二选一)
      this.form.id = scope.musicid;
      this.form.name = scope.music_name;
      this.form.singerId = scope.singer_id;
      this.form.musictypeId = scope.musictype_id;
      // 显示修改音乐的表单
      this.dialogFormVisibleEditMusic = true;
      // 获取musictype 为修改音乐做准备
      this.getMusicTypeL();
      // 获取singer 为修改音乐做准备
      this.getSingerL();
    },
    // 修改音乐
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.dialogFormVisibleEditMusic = false;
          // id name musictypeId singerId musicurl musicfile picfile (musicurl musicfile二选一)
          var formData = new FormData();
          formData.append('id', this.form.id);
          formData.append('name', this.form.name);
          formData.append('musictypeId', this.form.musictypeId);
          formData.append('singerId', this.form.singerId);
          formData.append('musicurl', this.form.musicurl);
          formData.append('picfile', this.form.picfile);
          formData.append('musicfile', this.form.musicfile);
          let res = await editMusic(formData);
          if (res.status == 0) {
            this.$message({
              message: '修改音乐信息成功！',
              type: 'success'
            });
            if (this.isHasMusicTypeId) {
              this.getMusicLByMusicType(this.currentMusicTypeId);
            } else {
              this.getMusicL();
            }
            this.form.name = '';
            this.form.musictypeId = '';
            this.form.singerId = '';
            this.form.musicurl = '';
            this.form.id = 0;
            this.form.musicfile = null;
            this.form.picfile = null;
            this.imageUrl = '';
            this.fileList = [];
          } else {
            this.$message.error(res.message);
          }
        }
      });
    },
    // 添加音乐
    submitAddMusicForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.dialogFormVisibleAddMusic = false;
          // name musictypeId singerId musicurl musicfile picfile (musicurl musicfile二选一)
          var formData = new FormData();
          formData.append('name', this.addForm.name);
          formData.append('musictypeId', this.addForm.musictypeId);
          formData.append('singerId', this.addForm.singerId);
          formData.append('musicurl', this.addForm.musicurl);
          formData.append('picfile', this.addForm.picfile);
          formData.append('musicfile', this.addForm.musicfile);
          let res = await addMusic(formData);
          if (res.status == 0) {
            this.$message({
              message: '添加音乐成功！',
              type: 'success'
            });
            if (this.isHasMusicTypeId) {
              this.getMusicLByMusicType(this.currentMusicTypeId);
            } else {
              this.getMusicL();
            }
            this.addForm.name = '';
            this.addForm.musictypeId = '';
            this.addForm.singerId = '';
            this.addForm.musicurl = '';
            this.addForm.musicfile = null;
            this.addForm.picfile = null;
            this.imageUrl = '';
            this.addMusicFileList = [];
          } else {
            this.$message.error(res.message);
          }
        }
      });
    },
    // 删除音乐
    handleDelete (id) {
      this.$confirm('此操作将永久删除该音乐, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await deleteMusic(id);
        if (res.status == 0) {
          this.$message({
            message: '删除音乐成功！',
            type: 'success'
          });
          if (this.isHasMusicTypeId) {
            this.getMusicLByMusicType(this.currentMusicTypeId)
          } else {
            this.getMusicL();
          }
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 获取全部音乐
    async getMusicL () {
      let res = await getMusicList();
      if (res.status == 0) {
        this.tableData = res.data;
        // 防止一上来第一个就显示暂停
        this.playIndex = this.tableData.length;
      } else {
        this.$message.error(res.message);
      }
    },
    // 根据音乐类型获取音乐
    async getMusicLByMusicType (id) {
      let res = await getMusicListByMusicTypeId(id);
      if (res.status == 0) {
        this.tableData = res.data;
        // 获取当前的音乐类型进行显示
        // 通过getMusicListByMusicTypeId获取有数据 正常获取当前的音乐类型进行显示
        if (res.data.length !== 0) {
          this.currentMusicType = res.data[0].musictype_name;
        } else {
          // 通过getMusicListByMusicTypeId获取的数据为0 因为该音乐类型中没有音乐 所以没包含MusicType名 可以在前面的页面传递MusicType名也可以重新根据musictypeid重新发起请求 这里使用后者
          let res1 = await getMusicTypeByMusicTypeId(id);
          this.currentMusicType = res1.data[0].musictype_name;
        }
        // 防止一上来第一个就显示暂停
        this.playIndex = this.tableData.length;
      } else {
        this.$message.error(res.message);
      }
    },
    // 试听 点击播放按钮
    handlePlay (scope, index) {
      // 如果正在播放音乐的表格行数不是获取到音乐时设置的值并且不是当前音乐的索引 说明别的歌曲正在播放
      if (this.playIndex !== this.tableData.length && this.playIndex !== index) {
        // 暂停播放
        this.$refs.audio.pause();
        // 修改playIndex为获取到音乐时设置的值 即防止显示暂停
        this.playIndex = this.tableData.length;
        if (scope.music_url !== null) {
          // 给audio赋值
          this.$refs.audio.src = scope.music_url;
          // 播放
          this.$refs.audio.play();
          // 显示暂停
          this.playIndex = index;
        } else {
          // 给audio赋值
          this.$refs.audio.src = 'http://localhost:3001/' + scope.music_file;
          // 播放
          this.$refs.audio.play();
          // 显示暂停
          this.playIndex = index;
        }
      } else if (this.playIndex !== this.tableData.length) {
        // 暂停播放
        this.$refs.audio.pause();
        // 修改playIndex为获取到音乐时设置的值 即防止显示暂停
        this.playIndex = this.tableData.length;
      } else {
        // 没有在播放
        // 查看music_url或music_file哪个有值 可以播放
        if (scope.music_url !== null) {
          // 给audio赋值
          this.$refs.audio.src = scope.music_url;
          // 播放
          this.$refs.audio.play();
          // 显示暂停
          this.playIndex = index;
        } else {
          // 给audio赋值
          this.$refs.audio.src = 'http://localhost:3001/' + scope.music_file;
          // 播放
          this.$refs.audio.play();
          // 显示暂停
          this.playIndex = index;
        }
      }
    },
    // 查看和获取评论
    async handleComment (id) {
      // type(0歌曲 1歌单 2mv) musicid gedanid mvid
      let res = await getComment(0, 'musicid', id);
      if (res.status == 0) {
        this.gridData = res.data;
      }
      this.dialogTableVisible = true;
    },
    // 删除评论
    async handleDeleteComment (id) {
      let res = await deleteComment(id);
      if (res.status == 0) {
        this.$message({
          message: '删除评论成功，请稍后查看！',
          type: 'success'
        });
      } else {
        this.$message.error(res.message);
      }
    },
    // 修改音乐准备上传文件的数据
    handleImageChange (file, filelist) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.picfile = filelist[filelist.length - 1].raw;
    },
    // 修改音乐准备上传文件的数据
    handleFileChange (file, filelist) {
      this.fileList = [filelist[filelist.length - 1]];
      this.form.musicfile = filelist[filelist.length - 1].raw;
    },
    // 音乐播放完毕
    endedPlay () {
      // 修改playIndex为获取到音乐时设置的值 即防止显示暂停
      this.playIndex = this.tableData.length;
    },
    // 添加音乐准备上传文件的数据
    handleFileChangeAddMusic (file, filelist) {
      this.addMusicFileList = [filelist[filelist.length - 1]];
      this.addForm.musicfile = filelist[filelist.length - 1].raw;
    },
    // 添加音乐准备上传文件的数据
    handleImageChangeAddMusic (file, filelist) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.addForm.picfile = filelist[filelist.length - 1].raw;
    }
  }
}
</script>

<style lang="less" scoped>
  .avatar-uploader /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  /deep/ .el-list-leave-active{
    transition: none;
  }
</style>